package m202405.d12;

import java.util.ArrayList;
import java.util.Comparator;

/**
 * @@author: 爱做梦的锤子
 * @date: 2024/5/12 18:16
 */
public class Q148 {

    public static void main(String[] args) {
        ListNode list1 = new ListNode(2);
        list1.next = new ListNode(4);
        list1.next.next = new ListNode(3);


        Q148 q148 = new Q148();
        ListNode listNode = q148.sortList(list1);
        System.out.println();
    }

    public ListNode sortList(ListNode head) {
        if (head == null) {
            return null;
        }
        if (head.next == null) {
            return head;
        }
        ListNode right = split(head);
        ListNode left = head;
        ListNode sl = sortList(left);
        ListNode sr = sortList(right);
        return merge(sl, sr);
    }

    private ListNode split(ListNode listNode) {
        ListNode slow = listNode;
        ListNode fast = listNode.next;
        while (fast != null && fast.next != null) {
            slow = slow.next;
            fast = fast.next.next;
        }
        ListNode res = slow;
        slow = slow.next;
        res.next = null;
        return slow;
    }

    private ListNode merge(ListNode l1, ListNode l2) {
        ListNode res = new ListNode();
        ListNode rp = res;
        while (l1 != null || l2 != null) {
            if (l1 == null) {
                rp.next = l2;
                l2 = l2.next;
                rp = rp.next;
                continue;
            }
            if (l2 == null) {
                rp.next = l1;
                l1 = l1.next;
                rp = rp.next;
                continue;
            }
            if (l1.val < l2.val) {
                rp.next = l1;
                l1 = l1.next;
            } else {
                rp.next = l2;
                l2 = l2.next;
            }
            rp = rp.next;
        }
        return res.next;
    }

    public ListNode sortList1(ListNode head) {
        ArrayList<ListNode> list = new ArrayList<>();
        ListNode p = head;
        while (p != null) {
            list.add(p);
            p = p.next;
        }
        list.sort(Comparator.comparingInt(l -> l.val));
        ListNode res = new ListNode();
        ListNode rp = res;
        for (ListNode listNode : list) {
            rp.next = listNode;
            rp = rp.next;
        }
        rp.next = null;
        return res.next;
    }
}
